<template>
  <div class="project-setting project-status-setting">
    <div class="setting-header-top">
      <div class="setting-title">
        <div class="setting-title-detail">{{ $t('projectManage.setting.taskSetting.preTaskTip') }}</div>
        <div class="title-btn">
          <span>{{ $t('projectManage.setting.taskSetting.tip3') }}</span>
          <span @click="goTaskType" class="link-text">{{ $t('projectManage.setting.taskSetting.tip4') }}</span>
        </div>
      </div>
      <div class="pre-task">
        <el-cascader
          ref="cascaderType"
          :options="allTypeOptions"
          :props="taskProps"
          collapse-tags
          filterable
          v-model="taskPreFormId"
          @change="typeChange"
          :placeholder="$t('projectManage.setting.taskSetting.placeholder3')"
          clearable></el-cascader>
      </div>
    </div>
    <div class="setting-header">
      <div class="setting-title-detail">
      {{ titleTip }}
      </div>
      <div class="setting-action">
        <el-button type="primary" @click="addOrEditTask('add')"><i class="el-icon-plus"></i> {{$t('projectManage.setting.taskSetting.createTask')}}</el-button>
      </div>
    </div>
    <div class="title-btn">{{ $t('projectManage.setting.taskSetting.tip5') }}</div>
    <div class="setting-content" v-loading="loading">
      <BaseListForNoData v-show="!loading && !tableData.length" :notice-msg="$t('common.base.tip.noData')"></BaseListForNoData>
      <template v-if="tableData.length">
        <div class="task-draggable">
          <el-table
            v-table-style
            row-key="id"
            :data="tableData"
            header-row-class-name="common-list-table-header__v2"
            border>

            <el-table-column type="index" width="50">
              <span class="moveEle"><i class="iconfont icon-tuozhuaipaixu" /></span>
            </el-table-column>
            <el-table-column
              v-for="(column, index) in columns"
              :key="`${column.displayName}_${index}`"
              :prop="column.fieldName"
              :label="column.displayName"
              :min-width="column.minWidth || '108px'"
              show-overflow-tooltip
              >
              <template slot-scope="scope">
                <template v-if="column.fieldName === 'taskType'">
                  {{ scope.row.taskTypeName }}{{ scope.row.taskFormName ? `/${scope.row.taskFormName}`: '' }}
                </template>
                <template v-else-if="column.fieldName === 'taskWeight'">
                  <el-input  type="text" v-model="scope.row.taskWeight" :placeholder="$t('common.base.tip.defaultPlaceholder')" @change="handleInputChange(scope.row)"></el-input>
                </template>
                <template v-else>
                  {{ $formatFormField(column, scope.row) }}
                </template>
              </template>
            </el-table-column>
            <el-table-column fixed="right" :label="$t('common.base.table.col.operator')" width="180px">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="addRule(scope.row)">{{$t('common.base.createRuler')}}</el-button>
                <el-button type="text" size="small" @click="addOrEditTask('edit',scope.row)">{{$t('common.base.edit')}}</el-button>
                <el-button class="danger-btn" size="small" type="text" @click="deleteRow(scope.row)">{{$t('common.base.delete')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </div>
    <!-- 新建任务弹窗 -->
    <create-task ref="CreateTaskModal" :typeOptions="typeOptions" :template-id="templateId" @submitTask="submitTask"></create-task>
    <!-- 新建规则弹窗 -->
    <create-rule ref="CreateRuleModal" :template-id="templateId" @submitRule="submitRule"></create-rule>
  </div>
</template>
<script>
import NoDataView from '@src/component/common/NoDataViewNew';
import CreateTask from '@src/modules/setting/projectManage/components/TaskSettings/components/CreateTask.vue'
import CreateRule from '@src/modules/setting/projectManage/components/TaskSettings/components/CreateRule.vue'


import { openAccurateTab } from '@src/util/platform';
import * as ProjectManage from '@src/api/ProjectManage.ts';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import _ from 'lodash';
import Sortable from 'sortablejs';

export default {
  name: 'task-settings',
  data() {
    return  {
      taskPreFormId: [], // 预先选中的任务类型
      tableData: [],// 表格的数据
      loading: false,
      titleTip: this.$t('projectManage.setting.taskSetting.setModuleTitle'),
      taskProps: {
        multiple: true,
        value: 'id',
        label: 'name',
        emitPath: false,
        children: 'formList',
      },
      allTypeOptions: [],
      typeOptions: [], // 弹窗内的列表
      originTaskTypeId: '', // 详情默认返回的任务类型id
    }
  },
  components: {
    NoDataView,
    CreateTask,
    CreateRule,
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    }
  },

  computed: {
    columns() {
      let columns = [
        {
          displayName: this.$t('projectManage.setting.taskSetting.taskName'),
          fieldName: 'projectTaskName',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.taskType'),
          fieldName: 'taskType',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.preTask'),
          fieldName: 'preTaskName',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.projectContent'),
          fieldName: 'projectTaskDesc',
          setting: {
            originalFormType: 'text',
          },
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.presetTaskWeight'),
          fieldName: 'taskWeight',
          minWidth: '150px',
          setting: {
            originalFormType: 'text',
          },
        },
      ];
      return columns;
    },
  },
  // 页面初始化
  mounted() {
    this.getTaskList() // 获取任务列表
    this.queryDetail()
    this.getQueryTaskType()
    this.getTaskTypeData()
  },
  methods: {
    /** 预设任务权重设置*/
    handleInputChange(row) {
      if (row.taskWeight < 0) {
        // 如果输入值为负数，则将输入框的值设为0
        row.taskWeight = 0;
      }
      this.saveTask(row, true)
    },
    // 行拖拽
    rowDrop() {
      // 此时找到的元素是要拖拽元素的父容器
      const tbody = document.querySelector('.task-draggable .el-table__body-wrapper tbody');
      const _this = this;
      Sortable.create(tbody, {
          //指定父元素下可被拖拽的子元素
          draggable: ".task-draggable .el-table__row",
          onEnd({newIndex, oldIndex}) {
            const currRow = _this.tableData.splice(oldIndex, 1)[0];
            _this.tableData.splice(newIndex, 0, currRow);
            _this.handleUpdateSort(currRow, newIndex, oldIndex)
          }
      });
    },

    // 跳转到任务模版库
    goTaskType() {
      let fromId = window.frameElement.getAttribute('id');
      openAccurateTab({
        type: PageRoutesTypeEnum.PageProjectManageTaskCartList,
        fromId,
      });
    },
    queryDetail() {
      let params = {
          projectTypeId: this.templateId,
          projectUserConfigEnum: 'TASK_TYPE'
        }
      ProjectManage.queryDetail(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.taskPreFormId = JSON.parse(res?.data?.config)
      })
    },
    // 获取弹窗过滤的可用任务类型
    getTaskTypeData() {
      ProjectManage.queryTaskType({projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)

        this.typeOptions = (res.data || []).map((item, index) => Object.freeze({
          id: index, // 解决默认选中所有的事件
          ...item
        }))
      })
    },
    // 获取任务类型列表
    getQueryTaskType() {
      ProjectManage.queryAllTaskType({projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.allTypeOptions = res.data || []
      })
    },
    getTaskList() {
      this.loading = true
      ProjectManage.taskList({projectTypeId: this.templateId}).then((res) => {
        this.loading = false
        if (!res.success) return this.$message.error(res.message)
        this.$set(this, 'tableData', res.data || [])
        if (this.tableData.length) {
          // 列表有数据的时候才渲染选择行
          this.$nextTick(() => {
            this.rowDrop()
          })
        }
      })
    },

    // 添加任务
    async addOrEditTask(type, item) {
      await this.getTaskTypeData()
      if (type === 'add') {
        this.$refs.CreateTaskModal.openDialog({}, false)
      } else {
        let params = {
          id: item.id,
          projectTypeId: this.templateId,
        }
        ProjectManage.taskItemDetail(params).then((res) => {
            if (!res.success) return this.$message.error(res.message)
            this.originTaskTypeId = res?.data?.taskFormId // 最开始的任务类型id
            this.$refs.CreateTaskModal.openDialog(res.data, true)
        })
      }
    },
    // 添加规则
    addRule(item) {
      this.$refs.CreateRuleModal.openDialog(item)
    },
    typeChange() {
        let params = {
          projectTypeId: this.templateId,
          config: JSON.stringify(this.taskPreFormId || []) ,
          projectUserConfigEnum: 'TASK_TYPE'
        }
        ProjectManage.saveTaskTypeConfig(params).then((res) => {
          if (!res.success) return this.$message.error(res.message)
        })
    },

    submitRule(list, taskId) {
      let params = {
        projectTypeId: this.templateId,
        id: taskId,
        insertFieldOptionsList: list,
      }
      ProjectManage.updateRule(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.$message.success(this.$t('common.base.tip.createSuccess2'));
        this.getTaskList()
      })
    },
    // 更新排序
    handleUpdateSort(item, newIndex, oldIndex) {
      // type 1 上拖 2 下拖
      let type = ((newIndex - oldIndex) > 0 ) ? 2 : 1

      // 向上拖动 取之后的第一个id 拖拽到第一个的话为null
      let swapAfterTaskId = null
      if (type === 1) {
        if (newIndex === 0) {
          // 如果拖拽到第一个的话，id就为null 
          swapAfterTaskId = null
        } else {
          let afterItem = this.tableData.find((value,index,arr)=>{
            // 向上拖拽，取上一个的id
            return index == (newIndex - 1)
          });
          swapAfterTaskId = afterItem.id
        }
      } else {
        if (newIndex === (this.tableData.length - 1)) {
          // 如果拖拽到最后一个的话，id就为null 
          swapAfterTaskId = null
        } else {
          let preItem = this.tableData.find((value,index)=>{
            // 向下拖拽，取下一个的id
            return index == (newIndex + 1)
          });
          swapAfterTaskId = preItem.id
        }
      }

      let params = {
        projectTypeId: this.templateId,
        swapTaskId: item.id, // 这个是被拖拽的id
        type: type,
        swapAfterTaskId: swapAfterTaskId, // 这个是拖拽之后上下的id
      }

      ProjectManage.taskSwapCheck(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)

        if (res.data.flag) {
          let messageCommon = this.$t('projectManage.setting.taskSetting.confirmMess2')
          this.$confirm(messageCommon, this.$t('common.base.toast'), {
            confirmButtonText: this.$t('common.base.makeSure'),
            cancelButtonText: this.$t('common.base.cancel'),
            type: 'warning',
          })
          .then(() => {

            this.updateOrder(params)
          })
          .catch(() => { 
            // 取消的话，更新列表
            this.getTaskList()
          });
        } else {
          this.updateOrder(params)
        }
      })
    },

    updateOrder(params) {
      let updateOrderList = this.tableData.map((item,index) => {
        return {
          id: item.id,
          orderNumber: (index + 1)
        }
      })

      let swapParams = {
        ...params,
        updateOrderList: updateOrderList
      }
      ProjectManage.taskSwap(swapParams).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.getTaskList()
      })
    },
    
    // 接口弹窗任务表单参数
    submitTask(form, isEdit) {
       let params = {
          ...form,
          projectTypeId: this.templateId,
      }
      if (isEdit) {
        let checkParams = {
          id: form.id,
          projectTypeId: this.templateId,
        }

        // 先判断任务类型是否被更改
        let isChangeTaskType = this.originTaskTypeId === form.taskFormId

        // 先判断当前任务是否创建了规则
        ProjectManage.editTaskCheck(checkParams).then((res) => {
          if (!res.success) return this.$message.error(res.message)
          if (res.data?.taskRuleId && !isChangeTaskType) {
            // 如果返回的有值，说明当前任务创建了规则
            this.$confirm(this.$t('projectManage.setting.taskSetting.tip2'), this.$t('common.base.toast'), {
              confirmButtonText: this.$t('common.base.makeSure'),
              cancelButtonText: this.$t('common.base.cancel'),
              type: 'warning',
            })
            .then(() => {
              this.saveTask(params)
            })
          } else {
            this.saveTask(params)
          }
        })
      } else {
        ProjectManage.taskAdd(params).then((res) => {
          if(res.success) {
            this.$message.success(this.$t('common.base.tip.createSuccess2'));
            this.$refs.CreateTaskModal.closeDialog()
            this.getTaskList()
          } else {
            this.$message.error(res.message || this.$t('common.base.tip.createError2'));
          }
        })
      }
    },

    // 保存任务
    saveTask(params, state) {
      ProjectManage.taskUpdate(params).then((res) => {
        // 关闭任务弹窗
        if(res.success) {
          if(!state) {
            this.getTaskList()
            this.$refs.CreateTaskModal.closeDialog()
            this.$message.success(this.$t('common.base.tip.editSuccess'));
          }
        } else {
          if(state) {
            this.getTaskList()
          }
          this.$message.error(res.message || this.$t('common.base.tip.editFail'));
        }
      })
    },
    
    // 删除任务
    deleteRow(item) {
      let messageCommon = this.$t('projectManage.setting.taskSetting.confirmMess1')
      this.$confirm(messageCommon, this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
      .then(() => {
        ProjectManage.taskDelete({projectTypeId: this.templateId, id: item.id}).then((res) => {
          if(res.success) {
            this.getTaskList()
            this.$message.success(this.$t('common.base.tip.deleteSuccess'));
          } else {
            this.$message.error(res.message || this.$t('common.base.tip.deleteFail'));
          }
        })
      })
      .catch(() => { });
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@src/modules/setting/projectManage/common/setCommon.scss';
.project-setting {
  .setting-header-top {
    margin-bottom: 20px;
    .pre-task {
      width: 508px;
      .el-cascader {
        width: 100%;
      }
    }
  }

  .setting-title-detail {
    font-size: 16px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #595959;
    line-height: 20px;
  }
  .title-btn {
      height: 40px;
      line-height: 40px;
      font-size: 14px;
      color: #595959;
      .link-text {
        color:$color-primary-light-6;
      }
    }
  .setting-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .setting-top {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #595959;
    line-height: 20px;
    margin-bottom: 20px;
    .task-cascader {
      width: 382px;
    }
  }
}
</style>